<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/24 0024
 * Time: 20:54
 */

namespace app\admin\controller;
use app\admin\model\AuthRule as AuthRuleModel;

class AuthRule extends Common
{
    protected $beforeActionList = [
        'delson'=>['only'=>'del'],
    ];

    public function lst(){
        $rule=new AuthRuleModel();
        $data=$rule->sort();
//        $data=$rule->paginate(10);
        $this->assign('res',$data);
        return view();
    }
    public function add(){
        $rules=db('auth_rule')->select();
        $this->assign("rules",$rules);
        if(request()->isPost()){
            $data=input('post.');
            $plevel=\db("auth_rule")->where('id',$data['pid'])->field('level')->find();
            if($plevel){
                $data['level']=$plevel['level']+1;
            }else{
                $data['level']=0;
            }
            $add=\db('auth_rule')->insert($data);
            if($add){
                $this->success('添加成功','lst');
            }else{
                $this->error('添加失败');
            }
        }
        return view();
    }
    public function edit(){
        $rule=new AuthRuleModel();
        $rules=$rule->sort();
        $id=input('id');
        $data=$rule->find($id);
        $this->assign("data",$data);
        $this->assign("rules",$rules);
        if(request()->isPost()){
            $data=input('post.');
            $plevel=\db("auth_rule")->where('id',$data['pid'])->field('level')->find();
            if($plevel){
                $data['level']=$plevel['level']+1;
            }else{
                $data['level']=0;
            }
            $edit=$rule->update($data);
            if($edit){
                $this->success('修改成功','lst');
            }else{
                $this->error('修改失败');
            }
        }
        return view();
    }
    public function del(){
        $rule=new AuthRuleModel();
        $id=input('id');
        $del=$rule->destroy($id);

        if($del){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
        return view();
    }
    public function delson(){
        $id=input('id');
        $rule=new AuthRuleModel();
        $rec=$rule->getChild($id);
        foreach ($rec as $k => $v){
            $res=$rule->where("id",$v)->delete();
            if(!$res){
                return $this->error("删除子权限时发生错误",'lst');
            }
        }
    }
}